package net.asfun.jvalog.resource;

import java.util.Collection;
import java.util.Date;

import javax.jdo.Query;

import net.asfun.jvalog.common.Jdoer;
import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Paper;
import net.asfun.jvalog.vo.Pager;

public class PaperDao {

	public static Paper getByUri(String uri) {
		Jdoer<Paper> jdp = JdoerFactory.jdoPaper;
		Query q = jdp.prepareQuery();
		q.setFilter("published == true && type == atype && uri == link");
		q.declareParameters("int atype, String link");
		return jdp.unique(q, Paper.POST_TYPE, uri);
	}

	public static Collection<Paper> listPublished(int type) {
		Jdoer<Paper> jdp = JdoerFactory.jdoPaper;
		Query q = jdp.prepareQuery();
		q.setFilter("published == true && type == atype");
		q.declareParameters("int atype");
		return jdp.more(q, type);
	}

	public static Paper getBySlogan(String slogan) {
		Jdoer<Paper> jdp = JdoerFactory.jdoPaper;
		Query q = jdp.prepareQuery();
		q.setFilter("published == true && type == atype && slogan == slo");
		q.declareParameters("int atype, String slo");
		return jdp.unique(q, Paper.PAGE_TYPE, slogan);
	}

	public static Collection<Paper> listPublished(int type, Pager pager) {
		Jdoer<Paper> jdp = JdoerFactory.jdoPaper;
		Query q = jdp.prepareQuery();
		q.setFilter("published == true && type == atype");
		q.declareParameters("int atype");
		pager.setTotal(jdp.more(q, type).size());
		q.setOrdering("date descending");
		q.setRange(pager.getStart(), pager.getEnd());
		return jdp.more(q, type);
	}

	public static Collection<Paper> listPublished(int type, int size) {
		Jdoer<Paper> jdp = JdoerFactory.jdoPaper;
		Query q = jdp.prepareQuery();
		q.setFilter("published == true && type == atype");
		q.declareParameters("int atype");
		q.setOrdering("date descending");
		q.setRange(0, size);
		return jdp.more(q, type);
	}

	public static Collection<Paper> listPublished(int type, Pager pager, Date afrom, Date ato) {
		Jdoer<Paper> jdp = JdoerFactory.jdoPaper;
		Query q = jdp.prepareQuery();
		q.setFilter("published == true && type == atype && date < ato && date > afrom");
		q.declareParameters("int atype, java.util.Date ato, java.util.Date afrom");
		pager.setTotal(jdp.more(q, type, afrom, ato).size());
		q.setOrdering("date descending");
		q.setRange(pager.getStart(), pager.getEnd());
		return jdp.more(q, type, ato, afrom);
	}

	public static Collection<Paper> listAll(int type, Pager pager) {
		Jdoer<Paper> jdp = JdoerFactory.jdoPaper;
		Query q = jdp.prepareQuery();
		q.setFilter("type == atype");
		q.declareParameters("int atype");
		pager.setTotal(jdp.more(q, type).size());
		q.setOrdering("date descending");
		q.setRange(pager.getStart(), pager.getEnd());
		return jdp.more(q, type);
	}
	
}
